import * as React from 'react'
import ScrollLock from 'react-scrolllock'
import { Modal, Toast } from 'antd-mobile'
import { Button, Item, NavBar, Gird, Icon, Switch } from 'components'
import { isArray, isEmptyObject, browser } from 'muka'
import './fillOrder.less'
import { post } from '../../utils'
// const alert = Modal.alert

export default class FillOrder extends React.Component<any, any> {
    public state = {
        checked: true,
        hdVal: 1000,
        payType: 1,
        visible: false,
        info: {},
        address: {},
        viewList: [],
        listVisible: false
    }

    // private hdVal: number = 0

    public render(): JSX.Element {
        const { checked, payType, visible, info, listVisible } = this.state
        const data: any = { ...info }
        const address: any = { ...this.props.defaultAddress }
        let title
        if (isEmptyObject(address)) {
            title = (
                <div>
                    <div className="name">请先添加地址</div>
                </div>
            )
        } else {
            title = (
                <div>
                    <div className="name">{address.name}    {address.tel}</div>
                    <div className="address">{address.province}{address.city}{address.area}{address.address}</div>
                </div>
            )
        }

        return (
            <div className="fill_order">
                <NavBar
                    className="header"
                    title="填写订单"
                    fixed={true}
                />
                <div className="fill_order_info">
                    <Gird style={{ padding: 0, margin: '0.4rem 0.5rem 0 0.5rem' }}>
                        <Item className="title" title={title} link="/my/address/3" />
                    </Gird>
                    <Gird style={{ padding: 0, margin: '0.4rem 0.5rem 0 0.5rem' }}>
                        <Item className="zhifu" title="支付方式" value={payType === 1 ? '在线支付' : '货到付款'} link={true} icon={<img className="more" src={require('../../assets/more.png')} />} onPress={() => { this.setState({ visible: true }) }} />
                    </Gird>
                    {
                        isArray(data.goodslist) && data.goodslist.map((item: any, index: number) => {
                            return (
                                <Gird style={{ padding: 0, margin: '0.4rem 0.5rem 0 0.5rem' }} key={index}>
                                    <Item className="item sh" title={<div><Icon type="shop" /> {item.seller_name}</div>} />
                                    <Item
                                        className="item auto"
                                        title=""
                                        extend={
                                            <div className="shop_info">
                                                <div className="flex">
                                                    {this.getNodeList(item.goodslist)}
                                                </div>
                                            </div>
                                        }
                                    />
                                    {/* <Item className="item" title="购买数量" value={<InputNumber min={0} />} /> */}
                                    <Item className="item" title="配送" value="快递运输" />
                                    <Item className="item int" title="留言" value={<input placeholder="建议留言前先与商家沟通确认" />} />
                                </Gird>
                            )
                        })
                    }

                    <Gird style={{ padding: 0, margin: '0.4rem 0.5rem 0 0.5rem' }}>
                        <Item
                            className="hd_switch"
                            title="恒豆"
                            value={
                                <div className="flex">
                                    <div className="flex_1">
                                        <div className="title_hd">共拥有10恒豆，可抵用¥1.00</div>
                                    </div>
                                    <div className="flex_justify">
                                        <Switch
                                            className="switch"
                                            checked={checked}
                                            onChange={this.handleSwitchChange}
                                        />
                                    </div>
                                </div>
                            }
                        />
                        {/* {this.getSwitchNode()} */}
                    </Gird>
                    <Gird style={{ padding: 0, margin: '0.4rem 0.5rem 0 0.5rem' }}>
                        <Item className="item" title="商品金额" value={<span className="DINPro">¥ {Number(data.price || 0).toFixed(2)}</span>} />
                        <Item className="item" title="恒豆可抵" value={<span className="DINPro" style={{ color: '#333333' }}>{data.price_q || 0}</span>} />
                        <Item className="item" title="运费" value={<span className="DINPro">¥ {Number(data.freight || 0).toFixed(2)}</span>} />
                    </Gird>
                </div>
                <div className="footer flex">
                    <div className="flex_justify flex_1">
                        <div>
                            <div className="flex_1">合计：<span className="number DINPro">¥{Number(data.price || 0 + data.freight || 0).toFixed(2)}+{data.price_q}</span><span className="hd">恒豆</span></div>
                        </div>
                    </div>
                    <Button onClick={this.handleMoveTo} className="btn">提交订单</Button>
                </div>
                <Modal
                    popup={true}
                    visible={visible}
                    animationType="slide-up"
                >
                    <div className="modal_header flex">
                        <div className="flex_1">支付方式</div>
                        <Icon type="close" onClick={() => { this.setState({ visible: false }) }} />
                    </div>
                    <div className="modal_info">
                        <Button className="btn" type={payType === 1 ? 'error' : undefined} onClick={this.setPayType.bind(this, 1)}>在线支付</Button>
                        {/* <Button className="btn" type={payType === 2 ? 'error' : undefined} onClick={this.setPayType.bind(this, 2)}>货到付款</Button> */}
                    </div>
                </Modal>
                {(visible || listVisible) && <ScrollLock />}
                {this.showListView()}
            </div>
        )
    }

    public componentDidMount() {
        this.getData()
    }

    private async getData() {
        try {
            const { SET_USER_DEFAULT_ADDRESS, defaultAddress } = this.props
            Toast.loading('', 0)
            const { userInfo } = this.props
            const params: any = browser.search
            let uri = 'orderapi/confirmOrder'
            if (params.type === '2') {
                uri = 'orderapi/repeatBuy'
            }
            const data = await post(uri, { ...params, userId: userInfo.id })
            if (!defaultAddress.id) {
                post('usersapi/userAddressStatus', {
                    userId: userInfo.id
                }).then((address: any) => {
                    SET_USER_DEFAULT_ADDRESS(address || {})
                })
            }
            setTimeout(() => { Toast.hide(); this.setState({ info: data }) }, 1000)
        } catch (e) {
            Toast.info('网络堵塞,请稍后重试', 2)
        }
    }

    private getNodeList(arr: any[] = []) {
        if (arr.length >= 2) {
            return arr.map((item: any, index: number) => {
                return (<img src={item.pic} key={index} onClick={() => { this.setState({ listVisible: true, viewList: arr }) }} />)
            })
        } else {
            return arr.map((item: any, index: number) => {
                return (
                    <React.Fragment key={index}>
                        <img src={item.pic} />
                        <div className="info flex_1">
                            <div className="title_l">{item.title}</div>
                            <div className="label">{item.spec}</div>
                            <div className="number">价格：<span className="DINPro">¥ {item.price}+{item.price_q}</span><span className="hd">恒豆</span><span className="num">x {item.number}</span></div>
                            <div className="hd_jg">恒豆：<img src={require('../../assets/hd_img.png')} />{item.all_price_q}</div>
                        </div>
                    </React.Fragment>
                )
            })
        }
    }

    private showListView() {
        const { viewList, listVisible } = this.state
        return (
            <Modal
                className="fill_order_modal"
                visible={listVisible}
                popup={true}
                animationType="slide-up"
            >
                <div className="flex header">
                    <div className="flex_1 label">商品清单</div>
                    <div className="value flex_justify">
                        <div>共{viewList.length}件<Icon type="close" style={{ position: 'relative', top: '0.1rem' }} onClick={() => { this.setState({ listVisible: false }) }} /></div>
                    </div>
                </div>
                {
                    viewList.map((item: any, index: number) => {
                        return (
                            <Item
                                key={index}
                                className="layList"
                                title=""
                                extend={
                                    <div className="shop_info">
                                        <div className="flex">
                                            <img src={item.pic} />
                                            <div className="info flex_1">
                                                <div className="title_l">{item.title}</div>
                                                <div className="label">{item.spec}</div>
                                                <div className="number">价格：<span className="DINPro">¥ {item.price}+{item.price_q}</span><span className="hd">恒豆</span><span className="num">x {item.number}</span></div>
                                                <div className="hd_jg">恒豆：<img src={require('../../assets/hd_img.png')} />{item.all_price_q}</div>
                                            </div>
                                        </div>
                                    </div>
                                }
                            />
                        )
                    })
                }
            </Modal>
        )
    }

    // private getSwitchNode() {
    //     const { checked, hdVal } = this.state
    //     if (checked) {
    //         return (
    //             <div className="hd_dk flex_justify">
    //                 <div>
    //                     使用<div className="hd_num DINPro" onClick={this.handleModel}><span>{hdVal}</span><Icon className="icon" type="arrow_down" /></div>恒豆，抵扣<span className="number DINPro">¥10.00</span>
    //                 </div>
    //             </div>
    //         )
    //     }
    //     return
    // }

    private handleSwitchChange = (checked: boolean) => {
        this.setState({
            checked
        })
    }

    // private handleModel = () => {
    //     const { hdVal } = this.state
    //     alert('请输入使用恒豆数量', <input type="number" className="mk_val_modal" defaultValue={hdVal.toString()} onChange={this.handleModalChange} />, [
    //         { text: '取消', onPress: () => console.log('cancel'), style: { color: '#333333', fontSize: '0.8rem', height: '2.2rem', lineHeight: '2.25rem' } },
    //         { text: '确定', onPress: this.handleOk, style: { background: '#f94009', color: '#fff', fontSize: '0.8rem', height: '2.2rem', lineHeight: '2.25rem' } },
    //     ])
    // }

    // private handleOk = () => {
    //     this.setState({
    //         hdVal: this.hdVal
    //     })
    // }

    // private handleModalChange = (e: any) => {
    //     this.hdVal = e.target.value
    // }

    private handleMoveTo = () => {
        const { history, userInfo, defaultAddress } = this.props
        const params = browser.search
        post('orderapi/goPay', {
            ...params,
            userId: userInfo.id,
            addressId: defaultAddress.id
        }).then((data: any) => {
            const { SET_BEANS_ORDER } = this.props
            const info: any = this.state.info
            Toast.info('订单提交成功', 2)
            setTimeout(() => { SET_BEANS_ORDER({ price: Number(info.price || 0 + info.freight || 0) }); history.push(`/selectPay/?id=3&orderId=${data}`) }, 2000)
        })
    }

    private setPayType(type: number) {
        this.setState({
            payType: type
        })
    }
}